import axios from "axios";
import { ElMessage, ElLoading ,ElNotification} from "element-plus";
import { Base64 } from "js-base64";
import useUserStore from "@/store/modules/user";
let request = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    // baseURL: "/mock",
    timeout: 5000
})



//加密token方法
function baseFun() {
    const token = localStorage.getItem("b0445-vue3-token");
    const base64 = Base64.encode(token + ":")
    return "Basic " + base64
}

//获取当前登录用户所属角色的最新权限
const getMenus = () => {
    const userStore = useUserStore()
    const roleId = userStore.user?.role_id;
    const userMenus = userStore.user?.role?.menus;

    if (userStore.user?.username == "admin") {
        return
    }
    //非超级管理员
    request({
        url: "/menus",
        method: 'post',
        data: {
            roleId,
        }
    }).then(resp => {
        if (resp.status == 0) {
            const menus = resp.data.menus
            if (userMenus?.length == menus.length) {
                userMenus?.forEach(item => {
                    if (menus.indexOf(item) == -1) {
                        userStore.removeUser()
                        ElMessage({
                            message: '当前登录的用户权限被修改，请重新登录',
                            type: "warning"
                        })
                        window.location.href = "/login"
                    }
                })
            } else {
                userStore.removeUser()
                ElMessage({
                    message: '当前登录的用户权限被修改，请重新登录',
                    type: "warning"
                })
                window.location.href = "/login"
            }
        }
        return
    })
}

//加载遮罩
const loading = {
    loadingInstance: null,
    open() {
        if (this.loadingInstance == null) {
            //@ts-ignore
            this.loadingInstance = ElLoading.service({
                text: '拼命加载中。。。',
                background: 'rgba(0, 0, 0, 0.5)',
            });
        }
    },
    close() {
        if (this.loadingInstance != null) {
            //@ts-ignore
            this.loadingInstance.close();
        }
        this.loadingInstance = null
    }
}

// 请求拦截器
request.interceptors.request.use(
    function (config) {
        const token = localStorage.getItem("b0445-vue3-token");
        if (token) {
            config.headers.authorization = baseFun()
        }
        if (config.url != "/menus" && config.url != "/login") {
            loading.open()
            getMenus()
        }
        return config;
    }, function (error) {
        loading.close()
        // Do something with request error
        return Promise.reject(error);
    });

// 响应拦截器
request.interceptors.response.use(function (response) {
    if(response.data.status != 0){
        ElNotification({
            title:'警告！',
            //@ts-ignore
            message:response.msg,
            type:"warning"
        })
    }
    loading.close()
    return response.data;

}, function (error) {
    loading.close()
    let msg = "";
    let status = error.response.status;


    switch (status) {
        case 401:
            msg = "token过期"
            break;
        case 403:
            msg = "无权访问"
            break;
        case 404:
            msg = "请求地址错误"
            break;
        case 500:
            msg = "服务错误"
            break;

        default:
            msg = "无网络"
            break;
    }
    ElMessage({
        type: 'error',
        message: msg
    })
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);

});
export default request